package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.netty.RequestHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {
    // 定义一个线程池
    private int corePoolSize = 10;
    private int maximumPoolSize = 50;
    private long keepAliveTime = 100L;
    private TimeUnit unit = TimeUnit.SECONDS;
    private BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
    private ThreadFactory threadFactory = Executors.defaultThreadFactory();
    private RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start(int port) throws Exception {
        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            socket.close();
        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/


        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    /**
     * netty实现
     *
     * @param port
     */
    public void nettyStart(int port) {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                // 无锁化串行编程
                // HttpResponseEncoder 编码器
                socketChannel.pipeline().addLast(new HttpResponseEncoder());
                // HttpRequestDecoder 解码器
                socketChannel.pipeline().addLast(new HttpRequestDecoder());
                // 业务逻辑处理
                socketChannel.pipeline().addLast(new RequestHandler(servletMap));
            }
        })
                // 针对主线程的配置 分配线程最大数量 128
                .option(ChannelOption.SO_BACKLOG, 128)
                // 针对子线程的配置 保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        try {
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("Tomcat start port:" + port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (null != workGroup) {
                workGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }
    }

    private Map<String, HttpServlet> servletMap = new HashMap<>();
    private static String webappsPath = Bootstrap.class.getResource("/").getPath();

    /**
     * 加载多个web容器
     *
     * @param path
     */
    private void loadMutilServlet(String path) {
        try {
            File file = new File(webappsPath + path);
            File[] fileList = file.listFiles();
            if (null != fileList && fileList.length > 0) {
                for (File curFile : fileList) {
                    if (curFile.isFile() && curFile.getName().equals("web.xml")) {
                        System.out.println("file is：" + curFile);
                        System.out.println(curFile.getPath());
                        System.out.println(path + "/" + curFile.getName());
                        loadServlet(webappsPath + path + "/", curFile.getName());
                    }
                    if (curFile.isDirectory()) {
                        //System.out.println("dir is ：" + curFile);
                        loadMutilServlet(path + "/" + curFile.getName());
                    }
                }
            } else {
                loadServlet(webappsPath, "web.xml");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(String appPath, String filename) throws Exception {
        InputStream resourceAsStream = new FileInputStream(appPath + filename);
        //InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
        SAXReader saxReader = new SAXReader();

        try {
            // create a URLClassLoader
            URLClassLoader loader = null;
            URL[] urls = new URL[1];
            File classPath = new File(appPath);
            // the forming of repository is taken from the
            // createClassLoader method in
            // org.apache.catalina.startup.ClassLoaderFactory
            String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
            // the code for forming the URL is taken from
            // the addRepository method in
            // org.apache.catalina.loader.StandardClassLoader.
            urls[0] = new URL(null, repository, (URLStreamHandler) null);
            loader = new URLClassLoader(urls);

            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.demo1.LagouServlet1</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClassStr = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                Class servletClass = loader.loadClass(servletClassStr);
                servletMap.put(urlPattern, (HttpServlet) servletClass.newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 加载解析相关的配置，web.xml
            webappsPath = "C:\\Users\\董红广\\Desktop\\minicat\\minicat\\src\\main\\resources\\";
            bootstrap.loadMutilServlet("");
            //bootstrap.loadMutilServlet("webapps");
            // 启动netty版
            bootstrap.threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    bootstrap.nettyStart(8081);
                }
            });
            // 启动Minicat
            bootstrap.threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        bootstrap.start(8080);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
